package com.jr.util;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.catalina.User;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Properties;

/**
 * 数据库工具类
 */
public class C3P0DBHelper{

    ComboPooledDataSource  ds = new ComboPooledDataSource("exampleDS");





    public Connection getCon(){
        try {
            return  ds.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return  null;
    }

    //7
    public void closeAll(Connection con, PreparedStatement ps, ResultSet rs) {
        try {
            if (rs != null) {
                rs.close();
            }
            if (ps != null) {
                ps.close();
            }
           if (con!=null){
               con.close();/*调的是归还*/
           }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


    //增删改的通用方法
    public int dtUpdate(String sql, Object... obj) { //3
        Connection con = getCon(); //1，2
        PreparedStatement ps = null;
        int count = 0;
        try {
            ps = con.prepareStatement(sql);//4
            for (int i = 0; i < obj.length; i++) {
                ps.setObject(i + 1, obj[i]);
            }
            count = ps.executeUpdate(); //5  6返回，谁调用谁处理
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeAll(con, ps, null); //7
        }
        return count;
    }

    //通用的查询方法
    public ArrayList dtQuery(String sql, Class cla, Object... obj) {
        ArrayList list = new ArrayList();
        Connection con = getCon();
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            ps = con.prepareStatement(sql);
            for (int i = 0; i < obj.length; i++) {
                ps.setObject(i + 1, obj[i]);
            }
            rs = ps.executeQuery();
            while (rs.next()) {
                Object o = cla.newInstance();
                Field[] fields = cla.getDeclaredFields();
                for (Field f : fields) {
                    f.setAccessible(true);
                    f.set(o, rs.getObject(f.getName()));
                }
                list.add(o);
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeAll(con, ps, rs);
        }
        return list;
    }

}
